import requests
import time
import hashlib
import bs4
from abuyun阿布云代理 import get_abuyun


class Cdut(object):

    def __init__(self,username,password,proxies = None):

        # 创建会话
        self.session = requests.session()

        # 记录账号信息
        self.username = username
        self.password = password
        self.proxies = proxies

    def login(self):
        # 头暂不需要
        headers = {

        }

        # post登陆请求的url
        login_post_url = 'http://202.115.133.173:805/Common/Handler/UserLogin.ashx'

        # 计算pwd值
        sign = str(round(time.time() * 1000))

        keymd5 = hashlib.md5()
        keymd5.update(self.password.encode())

        pwd = hashlib.md5()
        pwd.update((self.username + sign + keymd5.hexdigest()).encode())

        # 构建post_date
        post_date = {
            'Action': 'Login',
            'userName': self.username,
            'pwd': pwd.hexdigest(),
            'sign': sign,
        }

        # 发送请求
        res = self.session.post(url=login_post_url, data=post_date,proxies = self.proxies)

        # 登陆成功返回0, 失败返回1, 高峰期连接失败返回一段字符串
        if len(res.text) > 1:
            print('CDUT-login：',res.text)
            return False
        return not bool(eval(res.text))
        pass


    def logout(self):
        # 退出登陆,返回登陆页面
        loginOut_get_url = 'http://202.115.133.173:805/LoginOut.aspx'
        res = self.session.get(url=loginOut_get_url,proxies = self.proxies)
        res.encoding = 'utf-8'
        # print(res.text)

        # 结束会话，断开连接，释放资源
        self.session.close()


    def index(self):
        # 访问个人信息页面，验证登陆

        personal_get_url = 'http://202.115.133.173:805/Default.aspx'
        res = self.session.get(url=personal_get_url,proxies = self.proxies)
        res.encoding = 'utf-8'

        # 有学生名字，学号等信息应该成功
        # print(res.text)
        return res.content

    def student_infor(self):
        html = bs4.BeautifulSoup(self.index())
        return str(html.find(class_='student_infor'))

    def grade(self):
        pass


    def lesson(self):
        pass




def main():
    proxies = get_abuyun()
    student = Cdut('201702060122','452729199902090015',proxies)

    student.login()
    student.index()

    student.logout()


if __name__ == "__main__":
    # main()
    pass